#ifndef __OTPDB_H__
#define __OTPDB_H__

#include <stdint.h>
#include "ddm.h"

#define OTPDB_NAME "otp"
#pragma warning (disable:4200)
namespace DDM
{

struct OtpDBPara
{
    int dbType;
    char host[0x20];
    char user[0x20];
    char passwd[0x20];
    char dbname[0x20];
};

enum OTP_DB_ERR_TYPE
{
    ERR_NO,
    ERR_DB,
    ERR_NOINFO,
    ERR_BURNED_BEFORE,
    ERR_OTPDB_SETUP,
    ERR_OTPDB_MID_INVALID,
};

enum OTPDB_OTPTYPE
{
    OTPDB_OTPTYPE_AFINF,
    OTPDB_OTPTYPE_AFMUP,
    OTPDB_OTPTYPE_LSC,
    OTPDB_OTPTYPE_AWB,
    OTPDB_OTPTYPE_COLOR,
    OTPDB_OTPTYPE_AFSTART,
	OTPDB_OTPTYPE_MODULE,
};
enum OTPDB_CASEINFOTYPE
{
    OTPDB_CASEINFOTYPE_BURNFLAG,
    OTPDB_CASEINFOTYPE_MODVENDOR,
    OTPDB_CASEINFOTYPE_VCM,
    OTPDB_CASEINFOTYPE_VCMDRIVER,
    OTPDB_CASEINFOTYPE_LENS,
    OTPDB_CASEINFOTYPE_SENSOR,
    OTPDB_CASEINFOTYPE_PLATFORM,
};

#pragma pack(push, 1)
#define OTP_ITEM_MAGIC 0x55AACCEE
struct otp_item
{
    int magic;
    int type;
    int len;
    time_t tm;
    uint8_t data[0]; 
};
#pragma pack(pop)

class DDM_API OtpDB
{
public:
    static OtpDB* get_instance(int idx);

    int Connect(OtpDBPara &otpDBPara);
    void Close();
    bool IsOtpDbConnected(void);

    int GetModuleID(const char* SN, bool force=true);
    
    int update_sid(const char *sn, const char *SID);
    int get_sn_by_sid(const char* SID, char *SN, int max_len);
    int get_sid_by_sn(const char* sn, char *sid, int max_len);

    int UpdateOtpByType(int, int type, char *otp, int len);
    int GetOtpByType(int, int, char *, int, time_t *ptm = NULL);
    int get_otp_by_mid(int mid, void *out, int len);
    int update_otp_datetime(int mid, int type);
    
    int GetOtpBurnTime(int mid, time_t *time);
    int UpdateOtpBurnHistory(int mid);

    int lock_otp_data(int mid);
    int get_otp_data_lock_time(int mid, time_t *time);

    /* Warnning: for test use */
    int DBModuleInfoClear();
    int DBCaseInfoClear();
    int DBOtpBaseClear();
    int DBOtpBurnHistoryClear();

    const char* OtpDBError();
    int GetOtpDBErrorNo(){return otpdb_errno;}

    int get_sample_wb(const char *sn, int type, void *out);

    int setting_get(const char *opt, char *val, int valsize);
    int setting_get(const char *opt, int *val);
    int setting_get(const char *opt, double *val);
    int setting_set(const char *opt, const char *val);
    int setting_set(const char *opt, int val);
    int setting_set(const char *opt, double val);

private:
    OtpDB(int idx);
    OtpDBPara dbPara;
    DDM::Database *db;
    int otpdb_errno;
    DDM::Database *GetOtpDB();
    
    int idx;
    int do_get_mid(const char* SN);
    int UpdateModuleID(const char* SN);
};

extern "C"
{
DDM_API otp_item *get_otp_item(int type, void *in, int len);
}

}
#endif